<template>
  <div>
    <page-header title="赠送课程"></page-header>
    <div>
      <el-form
        :model="formData"
        label-width="120px"
        ref="form"
        :rules="rules"
        size="small">
        <el-form-item label="学号" prop="studentNo" style="width: 310px">
          <el-input v-model="formData.studentNo"></el-input>
        </el-form-item>
        <el-form-item label="关联课程" prop="courseId">
          <el-select
            filterable
            remote
            :remote-method="getCourseList"
            v-model="formData.courseId"
            placeholder="搜索课程">
            <el-option
              v-for="item in courseList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirmGive">确定赠送</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getCourseList } from '@/api/course';
import { giveCourse } from '@/api/base-config';

export default {
  data() {
    return {
      formData: {
        courseId: '',
        studentNo: '',
      },
      rules: {
        studentNo: [{ required: true, message: '请输入学生学号' }],
        courseId: [{ required: true, message: '请选择课程' }],
      },
      courseList: [],
    };
  },
  methods: {
    confirmGive() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            await giveCourse(this.formData);
            this.$message.success('赠送成功');
            this.$refs.form.resetFields();
          } catch (err) {
            console.log(err);
          }
        }
      });
    },
    async getCourseList(query) {
      if (query) {
        const { list } = await getCourseList({
          name: query,
          pageSize: 50,
          pageNum: 0,
          valid: 1,
        });
        this.courseList = list.map((item) => ({
          label: item.name,
          value: item.id,
        }));
      } else {
        this.courseList = [];
      }
    },
  },
};
</script>
